package stocks

import (
	"fmt"
	"html/template"

	"gitee.com/chenrh/finego/app"
	"gitee.com/chenrh/finego/backends/models"
	"gitee.com/chenrh/finego/backends/ui"
	"gitee.com/chenrh/finego/backends/utils"
	"gitee.com/chenrh/gotoolkit/conv"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	// "strings"
)

// StockCenterController 股票中心
type StockCenterController struct {
	// Optionally: context is auto-binded by Iris on each request,
	// remember that on each incoming request iris creates a new UserController each time,
	// so all fields are request-scoped by-default, only dependency injection is able to set
	// custom fields like the Service which is the same for all requests (static binding).
	Ctx iris.Context

	// Our UserService, it's an interface which
	// is binded from the main application.
	//Service services.UserService
}

// BeforeActivation 注册自定义的路由
func (c *StockCenterController) BeforeActivation(b mvc.BeforeActivation) {
	b.Handle("GET", "/center", "Center")
	b.Handle("POST", "/center/save_message", "SaveMessage")
}

// Center 用户股票中心
func (c *StockCenterController) Center() mvc.Result {

	_, user := utils.UserCache(c.Ctx)

	dbhelper := app.DB

	datasql := fmt.Sprintf("select a.grp_id, a.grp_name from stk_group a where a.user_id = '%d' order by a.order_num asc", user.UserID)
	grps, _ := dbhelper.Select(datasql)

	dict := map[string]interface{}{}
	dict["grp_id"] = "-1"
	dict["grp_name"] = "未分组"
	grps = append(grps, dict)

	stockssql := `select a.company_code, ifnull(b.grp_id,-1) grp_id, m.company_abbr, m.company_kind from stk_self_select a 
	left join stk_group_member b on a.company_code = b.company_code and b.user_id = %d
	left join stock_info m on a.company_code = m.company_code
	order by b.order_num, a.company_code asc`
	stockssql = fmt.Sprintf(stockssql, user.UserID)
	stocks, _ := dbhelper.Select(stockssql)

	for _, grp := range grps {
		arr := []map[string]interface{}{}
		for _, stk := range stocks {
			if conv.ToInt64(grp["grp_id"], -1) == conv.ToInt64(stk["grp_id"], -1) {
				one := map[string]interface{}{}
				one["abbr"] = stk["company_abbr"]
				one["code"] = stk["company_code"]
				one["kind"] = stk["company_kind"]
				arr = append(arr, one)
			}
		}
		grp["grp_abbr"] = arr
	}

	// 加载评论
	var pageindex int64 = conv.ToInt64(c.Ctx.URLParam("page"), 1) - 1
	var pagesize int64 = 15
	var datacount int64 = 0
	msgsql := fmt.Sprintf("select * from stk_message a where 1 = 1")
	cuntsql := fmt.Sprintf("select count(*) cnt from (%s) t", msgsql)

	arr, _ := app.DB.Select(msgsql+" order by a.created_at desc limit ?,?", pageindex*pagesize, pagesize)
	cnt, _ := app.DB.Select(cuntsql)

	if len(cnt) > 0 {
		datacount = cnt[0]["cnt"].(int64)
	}

	pagecontrol := ui.NewPagination(c.Ctx.Request(), datacount, pagesize)
	htmlpages := pagecontrol.Pages()

	return mvc.View{
		Name: "stocks/stocks.center.html",
		Data: iris.Map{
			"Title":        "用户股票中心",
			"GroupList":    grps,
			"CommentsRows": arr,
			"PageControl":  template.HTML(htmlpages),
		},
	}
}

// SaveMessage 保存评论
func (c *StockCenterController) SaveMessage() {

	content := c.Ctx.FormValue("content")
	haslogin, user := utils.UserCache(c.Ctx)

	if !haslogin {
		c.Ctx.JSON(iris.Map{"flag": false, "msg": "请选登录"})
		return
	}

	envmodel := models.STK_MESSAGE{
		USER_ID:     user.UserID,
		MSG_CONTENT: content,
	}
	envmodel.CreatedBy = user.NickName

	app.GetDB().Create(&envmodel)

	c.Ctx.JSON(iris.Map{"flag": true, "msg": "OK"})
	return
}
